/**
 * @description: 数据中台-任务-任务管理-新建任务
 * @author: hj
 * @update: hj(2020-01-14)
 */
import React from 'react';
import IceContainer from '@icedesign/container';
import {Button, Dialog,  Form, Grid,Input, Message, Radio,Pagination, Select,Table} from '@alifd/next';
import styles from './index.module.scss';
import event from '@/request'
import $http from '@/service/Services';
import {
    FormBinder as IceFormBinder,
    FormBinderWrapper as IceFormBinderWrapper,
    FormError as IceFormError,
} from '@icedesign/form-binder';
import FormItem from "antd/es/form/FormItem";
import AuthButton from "../../../../components/AuthComponent/AuthBotton";


const axios = $http;
const formItemLayout = {
    labelCol: {
        fixedSpan: 4
    },
    wrapperCol: {
        span: 22
    }
};
const {Option} = Select;
const {Group: RadioGroup} = Radio;
const {Row, Col} = Grid;
let form;

const Shape = {
    NO: 'normal',
    OFF: 'button'
};
const ItemDirection = {
    HORIZON: 'hoz',
    VERTICAL: 'ver'
};


/**
 * list
 */
class TaskEdit extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: {},
            id: '',
            buyFreeInfo: {},
            datasources: [],
            taskList: [],
            datasourceTypeId: '',
            schames: [],
            businessList: [],
            taskDetailList: [],
            sourceCheckedFreeTableList: [],
            sourceCheckedFreeTableIdList: [],
            targetCheckedFreeTableList: [],
            targetCheckedFreeTableIdList: [],
            targetColnums: [],
            sourceColnums: [],
            tableNameCondition: "",
            taskTableColumnVOS: [],
            config: {
                data: null,
                visible: false,
                title: '',
                content: ''
            }
        };
        // 当前页数
        this.pageNum = 1;
        this.$http = $http;
        // 分页每页显示数据条数
        this.pageSize = 10;
        // 数据总条数
        this.totalNum = 0;
        this.formChange = this.formChange.bind(this);
        this.validateAllFormField = this.validateAllFormField.bind(this);
        this.handleCheck = this.handleCheck.bind(this);
    }

    /**
     * 在渲染前调用,在客户端也在服务端
     */
    componentWillMount = () => {
        const params = new URLSearchParams(this.props.location.search);
        const id = params.get('id');
        this.setState({
            id: id,
        }, () => {
            this.getBusinessList();
            if (id) {
                const that = this;
                this.$http.get(event.event.url + '/v1/taskDetail/getTTaskDetailById/' + id)
                    .then(function (response) {
                        const {data} = response;
                        if (data.code === 1) {
                            Message.warning(data.message ? data.message : data.data);
                        } else {
                            that.setState({
                                value: data.data,
                                checkedFreeTableList: data.data.tableNames
                            })
                        }
                    })
                    .catch(function (error) {
                        Message.error(error.message);
                    })
            }
        });
    };
    /**
     * 根据id查询详情
     */
    getBusinessList = () => {
        const that = this;
        let urls = event.event.url + '/v1/platformBusiness/getPlatformBusinessList';
        this.$http.post(urls)
            .then(function (response) {
                const {data} = response;
                const arr = data.data;
                that.setState({
                    businessList: arr
                }, () => {
                    if (arr && arr.length > 0) {
                        that.getAllDatasourceList(arr[0].id);
                    }
                })
            })
            .catch(function (error) {
                Message.error(error.message);
            })
    };
    /**
     * 获取所有数据源列表
     */
    getAllDatasourceList = (businessId) => {
        const that = this;
        this.$http.get(event.event.url + '/v1/tDataSource/getAllDatasourceList/' + businessId).then(function (response) {
            const {data} = response;
            if (data.code === 1) {
                Message.warning(data.message ? data.message : data.data);
            } else {
                that.setState({
                    datasources: data.data
                })
            }
        })
            .catch(function (error) {
                Message.error(error.message);
            });
    };
    /**
     * 获取数据域
     * @param pageNum 分页
     * @param targe true 是目标数据表 false 是源数据表
     */
    getAllTableList = (pageNum) => {
        const that = this;
        const {value, target} = this.state;
        that.pageNum = typeof (pageNum) == 'number' ? pageNum : that.pageNum;
        this.$http.get(event.event.url + '/v1/tDataSource/getDatabaseBySourceId/' + that.pageSize + '/' + that.pageNum + '/' + (target ? value.targetId : value.datasourceId + "?name=" + this.state.tableNameCondition))
            .then(function (response) {
                const {data} = response;
                if (data.code === 1) {
                    Message.warning(data.message ? data.message : data.data);
                } else {
                    const arr = data.data.voList;
                    that.totalNum = data.data.total;
                    that.setState({
                        TableList: arr
                    })
                }
            })
            .catch(function (error) {
                console.error(error);
                Message.error(error.message);
            })
    };

    /* 表改变
    * @param formValue
    */
    formChange = (formValue) => {
        this.setState({
            value: formValue
        })
    };
    /**
     * 表验证
     */
    validateAllFormField = () => {
        const {value, checkedFreeTableList, sourceCheckedFreeTableIdList, targetCheckedFreeTableIdList, taskTableColumnVOS} = this.state;
        try {
            if (checkedFreeTableList.length = 0) {
                Message.warning('请填写必要的数据.');
                return;
            }
            value["sourceCheckedFreeTableIdList"] = sourceCheckedFreeTableIdList;
            value["targetCheckedFreeTableIdList"] = targetCheckedFreeTableIdList;
            value["taskTableColumnVOS"] = taskTableColumnVOS;
            const that = this;
            this.$http.post(event.event.url + '/v1/task/saveOrUpdateTaskDetail', value)
                .then(function (response) {
                    const {data} = response;
                    if (data.code === 1) {
                        Message.warning(data.message ? data.message : data.data);
                    } else {
                        Message.success('操作成功.');
                        that.props.history.go(-1);
                    }
                })
                .catch(function (error) {
                    console.error(error);
                    Message.error(error.message);
                })
        } catch (e) {
            console.error(e);
        }
    };

    /**
     *
     * @param keys
     * @param info
     */
    handleCheck(keys, info) {
        this.setState({
            checkedKeys: keys,
            info: info
        });
    }

    /**
     * 获取门店数据
     * @param pageNum
     */
    getTableList = (pageNum) => {
        this.getAllTableList(pageNum);
    }

    /**
     * 打开添加门店的弹窗
     */
    openAddTableDialog = (target) => {
        const {value} = this.state;
        if (!target) {
            if (value.datasourceId == undefined || value.datasourceId === '' || value.datasourceId == null) {
                Message.warning('请选择源数据库...');
                return;
            }
        } else {
            if (value.targetId == undefined || value.targetId === '' || value.targetId == null) {
                Message.warning('请选择目标数据库...');
                return;
            }
        }
        this.setState({
            target: target,
            checkedFreeTableIdList: [],
            checkedFreeTableList: [],
        }, () => {
            this.getTableList(1);
        })

        let arr = [];
        this.setState({
            checkedFreeTableIdList: [],
            checkedFreeTableList: [],
            addFreeTableDialogVisible: true,
            checkedTableIdList: []
        })
    };

    /**
     * 移除主数据表确定
     */
    okBuyTableCall = (index, record, target) => {
        let {sourceCheckedFreeTableList, targetCheckedFreeTableList} = this.state;
        if (target) {
            targetCheckedFreeTableList.splice(index, 1)
            this.setState({
                targetCheckedFreeTableList: targetCheckedFreeTableList,
            })
        } else {
            sourceCheckedFreeTableList.splice(index, 1)
            this.setState({
                sourceCheckedFreeTableList: sourceCheckedFreeTableList,
            })
        }

    };


    /**
     * 关闭赠送数据表的弹窗
     */
    onFreeTableClose = () => {
        this.setState({
            addFreeTableDialogVisible: false
        })
    }

    /**
     * 获取数据
     * @param targetCheckedFreeTableList
     * @param sourceCheckedFreeTableList
     */
    getTaskTableColumnVOS = (targetCheckedFreeTableList, sourceCheckedFreeTableList) => {
        const taskTableColumnVOS = [], target = targetCheckedFreeTableList.length > sourceCheckedFreeTableList.length;
        const maxArr = targetCheckedFreeTableList.length > sourceCheckedFreeTableList.length ? targetCheckedFreeTableList : sourceCheckedFreeTableList;
        const minArr = targetCheckedFreeTableList.length < sourceCheckedFreeTableList.length ? targetCheckedFreeTableList : sourceCheckedFreeTableList;
        for (let i = 0; i < maxArr.length; i++) {
            const maxObj = maxArr[i];
            let targetValue = target ? maxObj : {}, sourceValue = target ? {} : maxObj;
            for (let j = 0; j < minArr.length; j++) {
                const minObj = minArr[j];
                if (maxObj.name === minObj.name) {
                    targetValue = target ? targetValue : minObj;
                    sourceValue = target ? minObj : sourceValue;
                }
            }
            const obj = {
                sourceId: sourceValue.id,
                sourceName: sourceValue.name,
                sourceRemarks: sourceValue.remarks,
                sourcejdbcTypename: sourceValue.jdbcTypename,
                targetId: targetValue.id,
                targetName: targetValue.name,
                targetRemarks: targetValue.remarks,
                targetJdbcTypename: targetValue.jdbcTypename,
            };
            taskTableColumnVOS.push(obj);
        }
        return taskTableColumnVOS;
    }

    /**
     * 选择目标
     */
    changeSourceName = (record, value) => {
        const {sourceCheckedFreeTableList} = this.state;
        console.log(record, value);
        for (var i = 0; i < sourceCheckedFreeTableList.length; i++) {
            // record.targetId = target ? maxObj.id : null;
            // record.targetName = arget ? maxObj.id : null;
            // record.targetRemarks = target ? maxObj.id : null;
            // record.targetJdbcTypename = target ? maxObj.id : null;
        }

    };

    /**
     * 选择目标值
     */
    changeTargetName = (record, value) => {
        record.targetId = target ? maxObj.id : null;
        record.targetName = arget ? maxObj.id : null;
        record.targetRemarks = target ? maxObj.id : null;
        record.targetJdbcTypename = target ? maxObj.id : null;
    }
    /**
     * 赠送数据表确定事件
     */
    onFreeTableOk = () => {
        const {target, checkedFreeTableIdList, checkedFreeTableList, targetColnums, sourceColnums} = this.state;
        const that = this;
        axios.get(event.event.url + '/v1/tDatasourceTable/getTableColumnsSelect/' + checkedFreeTableIdList[0])
            .then(function (response) {
                const {data} = response;
                if (data.code === 1) {
                    Message.warning(data.message ? data.message : data.data);
                } else {
                    const arr = data.data.map(function (os) {
                        return {
                            label: os.name,
                            value: os.id,
                            ...os
                        }
                    });
                    if (target) {
                        that.setState({
                            addFreeTableDialogVisible: false,
                            targetColnums: arr,
                            targetCheckedFreeTableIdList: checkedFreeTableIdList,
                            targetCheckedFreeTableList: checkedFreeTableList,
                            taskTableColumnVOS: that.getTaskTableColumnVOS(data.data, sourceColnums),
                        })
                    } else {
                        that.setState({
                            addFreeTableDialogVisible: false,
                            sourceColnums: arr,
                            sourceCheckedFreeTableIdList: checkedFreeTableIdList,
                            sourceCheckedFreeTableList: checkedFreeTableList,
                            taskTableColumnVOS: that.getTaskTableColumnVOS(targetColnums, data.data),
                        })
                    }
                }
            })
            .catch(function (error) {
                console.error(error);
                Message.error(error.message);
            })
        this.setState({
            addFreeTableDialogVisible: false,
            checkedFreeTableIdList: checkedFreeTableIdList
        })
    };


    /**
     * 选中赠送数据表事件
     * @param value
     * @param data
     * @param extra
     */
    freeTableChange = (value, data, extra) => {
        const {target} = this.state;
        this.setState({
            checkedFreeTableIdList: value,
            checkedFreeTableList: data,
        })
    }
    /**
     * 分页大小改变执行
     * @param pageSize
     */
    onPageSizeChange =(pageSize)=>{
        this.pageSize = pageSize;
        this.pageNum = 1;
        this.getTableList();
    };
    /**
     * 数据表分页
     * @param currentPage
     */
    onTableChangePage = (currentPage) => {
        this.getTableList(currentPage);
    };

    /**
     * 修改数据类型
     * @param value 新的值
     * @param event 事件
     */
    changeBusiness = (value, event) => {
        this.getAllDatasourceList(value);
    };

    /**
     * biao
     * @param name
     */
    onNameChange = () => {
        this.getAllTableList(1);
    }
    /**
     *
     * @param value
     */
    searchAppUserChange = (value) => {
        this.setState({
            tableNameCondition: value
        })
    };

    /**
     * 表
     * @returns {*}
     */
    render() {
        const {buyFreeInfo, sourceCheckedFreeTableList, targetCheckedFreeTableList, taskTableColumnVOS} = this.state;
        return (
            <div>
                <div className='container-header'>
                    <p style={{display: 'inline-block'}}>新建任务</p>
                    <Button type="normal" size="small" className='next-btn-normal table-btn-return'
                            style={{float: 'right'}}>
                        <a onClick={() => {
                            this.props.history.go(-1)
                        }}> 返回</a>
                    </Button>
                </div>
                <IceContainer className='container-main'>
                    <IceFormBinderWrapper
                        value={this.state.value}
                        onChange={this.formChange}
                        ref={formRef => form = formRef}
                    >
                        <div className={styles.formContent}>
                            <h4 className={styles.dTitle}>基本信息设置</h4>
                            <div className={styles.formItem}>
                                <div className={styles.formLabel}><span className={styles.red}>*</span>任务名称：</div>
                                <IceFormBinder required name="businessId" message="业务不能为空">
                                    <Input name="name" className={styles.inputNme} placeholder="请填写活动名称" style={{width: 400}}
                                           aria-required="true"/>
                                </IceFormBinder>
                                <div className={styles.formError}>
                                    <IceFormError name="sourceType"/>
                                </div>
                            </div>
                            <div className={styles.formItem}>
                                <div className={styles.formLabel}><span className={styles.red}>*</span>数据源类型：</div>
                                <IceFormBinder required name="businessId" message="数据源类型不能为空">
                                    <Select name={'businessId'}
                                        placeholder="请选择"
                                        className={styles.inputNme}  onChange={this.changeBusiness}
                                    >
                                        {
                                            this.state.businessList.map(
                                                o => {
                                                    return (<Option value={o.id}>{o.name}</Option>)
                                                }
                                            )
                                        }
                                    </Select>
                                </IceFormBinder>
                                <div className={styles.formError}>
                                    <IceFormError name="businessId"/>
                                </div>
                            </div>
                            <div className={styles.formItem}>
                                <div className={styles.formLabel}><span className={styles.red}>*</span>源数据库：</div>
                                <IceFormBinder required name="datasourceId" message="源数据库不能为空">
                                    <Select name={'datasourceId'}
                                            placeholder="请选择"
                                            className={styles.inputNme}
                                    >
                                        {
                                            this.state.datasources.map(
                                                o => {
                                                    return (<Option value={o.id}>{o.name}</Option>)
                                                }
                                            )
                                        }
                                    </Select>
                                </IceFormBinder>
                                <div className={styles.formError}>
                                    <IceFormError name="datasourceId"/>
                                </div>
                            </div>

                            <div className={styles.formItem}>
                                <div className={styles.formLabel}><span className={styles.red}>*</span>目标数据库：</div>
                                <IceFormBinder required name="targetId" message="目标数据库不能为空">
                                    <Select name={'targetId'}
                                            placeholder="请选择"
                                            className={styles.inputNme}
                                    >
                                        {
                                            this.state.datasources.map(
                                                o => {
                                                    return (<Option value={o.id}>{o.name}</Option>)
                                                }
                                            )
                                        }
                                    </Select>
                                </IceFormBinder>
                                <div className={styles.formError}>
                                    <IceFormError name="targetId"/>
                                </div>
                            </div>
                            <div className={styles.formItem}>
                                <div className={styles.formLabel}>任务描述：</div>
                                <IceFormBinder
                                    name="content"
                                >
                                    <Input.TextArea
                                        maxLength={50}
                                        rows={8} style={{width: '400px'}} name={'content'}
                                        hasLimitHint
                                        placeholder="请填写任务描述信息"
                                        className={styles.inputNme}
                                    />
                                </IceFormBinder>
                                <div className={styles.formError}>
                                    <IceFormError name="content"/>
                                </div>
                            </div>



                            {/***********************源数据库 ***********************************/}
                            <p className='form-title'>源数据库</p>
                            <div className={styles.formItem}>
                                <div className={styles.formLabel}><span className={styles.red}>*</span>源数据库：</div>
                                <AuthButton auth={''}
                                            type="primary"
                                            title={'添加数据表'}
                                            onClick={() => this.openAddTableDialog(false)}
                                />
                            </div>
                            <div className={styles.formItem}>
                                <IceFormBinder  name={"sourceTableList"} >
                                    <Table dataSource={sourceCheckedFreeTableList} hideOnlyOnePage primaryKey="id" size="small"
                                           fixedHeader
                                           maxBodyHeight={400}>
                                        <Table.Column align="center" title="数据表" dataIndex="name"/>
                                        <Table.Column align="center" title="增量识别字段" dataIndex="incrementColumn"/>
                                        <Table.Column align="center" title="操作" cell={
                                            (value, index, record) => {
                                                return (
                                                    <div>
                                                        <AuthButton auth={''}
                                                                    type="primary"
                                                                    onClick={this.okBuyTableCall.bind(this, index, record, false)}
                                                                    title={'删除'}/>
                                                    </div>
                                                )
                                            }
                                        }/>
                                    </Table>
                                </IceFormBinder>
                            </div>
                            {/***********************源数据库 ***********************************/}

                            {/***********************目标数据库 ***********************************/}
                            <p className='form-title'>目标数据库</p>
                            <div className={styles.formItem}>
                                <div className={styles.formLabel}><span className={styles.red}>*</span>选择数据表：</div>
                                <AuthButton auth={''}
                                            type="primary"
                                            title={'添加数据表'}
                                            onClick={() => this.openAddTableDialog(true)}
                                />
                            </div>
                            <div className={styles.formItem}>
                                <IceFormBinder  name={"sourceTableList"} >
                                    <Table dataSource={targetCheckedFreeTableList} hideOnlyOnePage primaryKey="id" size="small"
                                           fixedHeader
                                           maxBodyHeight={400}>
                                        <Table.Column align="center" title="数据表" dataIndex="name"/>
                                        <Table.Column align="center" title="增量识别字段" dataIndex="incrementColumn"/>
                                        <Table.Column align="center" title="操作" cell={
                                            (value, index, record) => {
                                                return (
                                                    <div>
                                                        <AuthButton auth={''}
                                                                    type="primary"
                                                                    onClick={this.okBuyTableCall.bind(this, index, record, true)}
                                                                    title={'删除'}/>
                                                    </div>
                                                )
                                            }
                                        }/>
                                    </Table>
                                </IceFormBinder>
                            </div>
                            {/***********************目标数据库 ***********************************/}

                            {/***********************数据表列表 ***********************************/}
                            <p className='form-title'>数据表列表</p>
                            <div className={styles.formItem}>
                                <div className={styles.formLabel}><span className={styles.red}>*</span>数据表列表：</div>

                            </div>
                            <div className={styles.formItem}>
                                <IceFormBinder  name={"sourceTableList"} >
                                    <Table dataSource={taskTableColumnVOS} hideOnlyOnePage primaryKey="id" size="small"
                                           fixedHeader
                                           maxBodyHeight={400}>
                                        <Table.Column align="center" title="源数据表列" dataIndex="sourceName" cell={
                                            (value, index, record) => {
                                                return (
                                                    <Select placeholder="源数据表列"
                                                            defaultValue={record.sourceName}
                                                            value={record.sourceName}
                                                            id={record.sourcetId}
                                                            showSearch hasClear
                                                            onChange={this.changeSourceName.bind(this, record)}
                                                            dataSource={this.state.sourceColnums}
                                                            size="medium"
                                                            className="table-btn-select"
                                                    />
                                                )
                                            }
                                        }/>
                                        <Table.Column align="center" title="源数据表列备注" dataIndex="sourceRemarks"/>
                                        <Table.Column align="center" title="源数据表列类型" dataIndex="sourcejdbcTypename"/>
                                        <Table.Column align="center" title="目标表列" dataIndex="targetName" cell={
                                            (value, index, record) => {
                                                return (
                                                    <Select placeholder="目标数据表列"
                                                            id={record.targetId}
                                                            defaultValue={record.targetName}
                                                            value={record.targetName}
                                                            showSearch hasClear
                                                            onChange={this.changeTargetName.bind(this, record)}
                                                            dataSource={this.state.targetColnums}
                                                            size="medium"
                                                            className="table-btn-select"
                                                    />
                                                )
                                            }
                                        }/>
                                        <Table.Column align="center" title="目标表列备注" dataIndex="targetRemarks"/>
                                        <Table.Column align="center" title="目标表列类型" dataIndex="targetJdbcTypename"/>
                                        <Table.Column align="center" title="操作" cell={
                                            (value, index, record) => {
                                                return (
                                                    <div>
                                                        <AuthButton auth={''}
                                                                    type="primary"
                                                                    onClick={this.okBuyTableCall.bind(this, index, record)}
                                                                    title={'删除'}/>
                                                    </div>
                                                )
                                            }
                                        }/>
                                    </Table>
                                </IceFormBinder>
                            </div>
                            {/***********************目标数据库 ***********************************/}
                            <Row>
                                <Col style={{textAlign: 'left', marginTop: '20px'}}>
                                    <Form.Submit className='pipe-btn-submit' type="primary" validate
                                                 onClick={this.validateAllFormField}
                                                 style={{marginRight: '5px'}}>提交</Form.Submit>
                                </Col>
                            </Row>
                        </div>
                        <Dialog
                            title="添加数据表"
                            className={styles.addTableStyle}
                            visible={this.state.addFreeTableDialogVisible}
                            isFullScreen={true}
                            onOk={this.onFreeTableOk}
                            onCancel={this.onFreeTableClose}
                            onClose={this.onFreeTableClose}
                        >
                            <Form
                                ref={formRef => form = formRef}
                            >
                                <p>数据表名称：</p>
                                <FormItem>
                                    <Input name={"name"} className={styles.inputNme} placeholder="数据表名称"
                                           style={{width: 400}}
                                           aria-required="true" value={this.state.tableNameCondition}
                                           onChange={this.searchAppUserChange}/>
                                    <AuthButton auth={""}
                                                type="primary"
                                                title={"查询"} onClick={this.onNameChange.bind(this, 1)}/>
                                </FormItem>
                                <Table dataSource={this.state.TableList} hideOnlyOnePage primaryKey="id" size="small"
                                       rowSelection={{
                                           mode: 'single',
                                           onChange: this.freeTableChange,
                                           selectedRowKeys: this.state.checkedFreeTableIdList
                                       }}
                                >
                                    <Table.Column align="center" width={"120"} title="表名" dataIndex="comment"/>
                                    <Table.Column align="center" title="数据表" dataIndex="name"/>
                                    <Table.Column align="center" width={"120"} title="增量识别字段"
                                                  dataIndex="incrementColumn"/>
                                </Table>
                                <Pagination defaultCurrent={1}
                                            current={this.pageNum}
                                            pageSize={this.pageSize}
                                            total={this.totalNum}
                                            onChange={this.onTableChangePage}
                                            onPageSizeChange={this.onPageSizeChange}
                                            pageSizeList={[5,10,20,50,100,200]}
                                            hideOnlyOnePage
                                            pageSizeSelector="dropdown"
                                            className="page-demo"
                                            size="small"
                                />
                            </Form>

                        </Dialog>
                    </IceFormBinderWrapper>
                </IceContainer>
            </div>
        );
    }

}

export default TaskEdit;
